package com.shanghaionstar.carmanage.presenter;

import android.text.TextUtils;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.poi.Coordinate;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.iview.IChargingPileDetailView;
import com.shanghaionstar.carmanage.model.ChargePileStationEntity;
import com.shanghaionstar.carmanage.service.ChargePileDetailService;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.PoiHistoryInfo;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NavHolder;

import rx.functions.Action1;

/**
 * Created by 7828wc on 16/8/1.
 */
public class ChargingPileDetailPresenter extends BasePresenter<String> {

    private AbstractMapActivity mContext;
    private IChargingPileDetailView mChargingView;

    private ChargePileStationEntity chargePileStationEntity;
    private PoiItemInfo poiItemInfo = new PoiItemInfo();
    private FavoriteEntity favoriteEntity = new FavoriteEntity();

    private ChargePileDetailService service;
    private NavService navService;

    public ChargingPileDetailPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<String> view) {
        super.setView(view);
        this.mChargingView = (IChargingPileDetailView) view;
        mContext = (AbstractMapActivity) view.onActivity();
        service = new ChargePileDetailService(mContext);
        navService = new NavService(mContext);
    }



    public PoiItemInfo getPoiItemInfo(ChargePileStationEntity chargePileStationEntity){
        PoiItemInfo poiItemInfo = new PoiItemInfo();
        poiItemInfo.setLatitude(Double.parseDouble(chargePileStationEntity.getLatitude()));
        poiItemInfo.setLongitude(Double.parseDouble(chargePileStationEntity.getLongitude()));
        poiItemInfo.setTitle(chargePileStationEntity.getStationName());
        poiItemInfo.setAddress(chargePileStationEntity.getAddress());
        poiItemInfo.setCityName(chargePileStationEntity.getCity());
        return poiItemInfo;
    }

    public FavoriteEntity poiItemInfoToFavoriteEntity(PoiItemInfo info) {
        FavoriteEntity entity = new FavoriteEntity();
        Coordinate coordinate = new Coordinate();
        DeviceUtil device = new DeviceUtil(mContext);
        coordinate.setLatitude(info.getLatitude());
        coordinate.setLongitude(info.getLongitude());
        entity.setPoiCoordinate(coordinate);
        entity.setPoiCityCode(info.getCityName());
        entity.setDeviceID(device.getDeviceID());
        entity.setPoiPhoneNumber("");
        entity.setPoiAddress(info.getAddress());
        entity.setIdpID(ApplicationUtil.getInstance().getIdpID());
        entity.setPoiNickname(info.getAddress());
        entity.setPoiCatetory("");
        entity.setProvience("");
        entity.setPoiName(info.getTitle());
        return entity;
    }

    public void initData(ChargePileStationEntity chargePileStationEntity){
        poiItemInfo = getPoiItemInfo(chargePileStationEntity);
        favoriteEntity = poiItemInfoToFavoriteEntity(poiItemInfo);
        mChargingView.initView(chargePileStationEntity);
    }

    public void addFavoriteDestination(){
        view.setLoading(true);
        subscription = service.addFavoriteDestination(favoriteEntity)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        view.setLoading(false);
                        if(!TextUtils.isEmpty(s)){
                            mChargingView.onReponseSuccess(s);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        view.setLoading(false);
                        if(mChargingView != null && throwable != null) {
                            mChargingView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

    public  void sendTbtOrOdd(){
        sendTbtOrOdd(poiItemInfo);
    }

    public void sendTbtOrOdd(final PoiItemInfo poiItemInfo) {
        if(ApplicationUtil.getInstance().isCommanding){
            ApplicationUtil.getInstance().controlCommand(mContext);
            return;
        }else {
            ApplicationUtil.getInstance().isCommanding = true;
        }
        NavInfoModel navInfoModel = new NavInfoModel();
        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mContext)) {
            if (PreferencesUtls.getInstance(mContext).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
            } else if (PreferencesUtls.getInstance(mContext).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
            }
        } else {
            navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
        }
        navInfoModel.poiItemInfo = poiItemInfo;
        if (validateTbtOrOdd(poiItemInfo, navInfoModel.remoteCommandsType)) {
            new AuthorUtil().reauthForNoPin(mContext, new Action1() {
                @Override
                public void call(Object o) {
                    NavInfoModel tmp = new NavInfoModel();
                    if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mContext)) {
                        if (PreferencesUtls.getInstance(mContext).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                        } else if (PreferencesUtls.getInstance(mContext).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
                        }
                    } else {
                        tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                    }
                    tmp.poiItemInfo = poiItemInfo;
                    doNavCommand(tmp);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    ApplicationUtil.getInstance().isCommanding = false;
                    if (mChargingView != null) {
                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(mContext, new HttpException("", throwable.getMessage()));
                        mChargingView.onResponseError(new OnStarException("", errorInfo.getMsg()));
                    }
                }
            });
        }
    }

    /**
     * @param
     * @return void
     * @Title: saveSearchHistory
     * @Description: 保存到历史记录中
     */
    public void saveSearchHistory(PoiItemInfo poiItemInfo) {
        SearchHistoryImpl impl = new SearchHistoryImpl(mContext);
        impl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);

    }

    public void saveHistoryToSql(String requestId, PoiItemInfo poiItemInfo, String status, boolean isSave) {
        PoiHistoryInfo historyInfo = new PoiHistoryInfo();
        historyInfo.setPoiItemInfo(poiItemInfo);
        if (isSave) {
            historyInfo.setStatus("inProgress");
        } else {
            historyInfo.setStatus(status);
        }
        TBTHistoryImpl impl = new TBTHistoryImpl(mContext);
        impl.saveOrUpdateModelDestinationHistory(requestId, historyInfo, isSave);
    }


    private void doNavCommand(final NavInfoModel navInfoModel) {
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            saveSearchHistory(navInfoModel.poiItemInfo);
                        }
                        if (mChargingView != null) {
                            mChargingView.showCommandLoading(true);
                        }
                        NavHolder.getInstance(mContext).setCurrentSendPoi(navInfoModel.poiItemInfo);

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (mChargingView != null) {
                            mChargingView.onResponseError((OnStarException) throwable);
                            if (ApplicationUtil.isActivityFront()) {
                                mChargingView.showAppFrontNavCommandFailToast(NavHolder.getInstance(mContext).getCurrentSendPoi());
                            } else {
                                mChargingView.showAppBackNavCommandFailToast(NavHolder.getInstance(mContext).getCurrentSendPoi());
                            }
                        }
                    }
                });
    }

    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
        if (poiItemInfo == null) return false;
        if (remoteCommandsType != RemoteCommandsType.COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
            return false;
        if (!ApplicationUtil.getInstance().isLogin())
            return false;
        if (ApplicationUtil.getInstance().isAutoLogings()) {
            if (mChargingView!= null) {
                mChargingView.onResponseError(new OnStarException("", mContext.getString(R.string.loading)));
            }
        }
        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mContext)) {
            return false;
        }
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, mContext, true)) {
            return false;
        }
        //判断是否正在执行车辆的相关操作
        if (BusinessUtil.checkInProgressCommand(mContext, null, false)) {
            AlertDialogUtil.showAlertDialog(mContext, mContext.getString(R.string.dialog_warning),
                    mContext.getString(R.string.service_inProcess_alert));
//            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", mContext);
            return false;
        }
        return true;
    }


}
